package com.demo.function.mybatis.mybatisplus.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.mapper.UserMapper;
import com.demo.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserService extends ServiceImpl<UserMapper, User> {

    /**
     * 批量更新，默认更新批次是1000
     * @param user 更新参数
     */
    public void updateBatch(List<User> user) {
        this.updateBatchById(user);
    }

    /**
     * 批量更新
     * @param user 更新参数
     * @param batchSize 自定义更新批次
     */
    public void updateBatch(List<User> user, int batchSize) {
        this.updateBatchById(user, batchSize);
    }

    /**
     * 批量保存，自定义保存记录总数
     * @param totalRecord 总记录数
     */
    public List<User> saveBatchByParam(int totalRecord) {
        List<User> list = new ArrayList<>();
        for (int i = 0; i < totalRecord; i++) {
            User user = new User();
            user.setUserName("name" + i);
            list.add(user);
        }

        long startTime = System.currentTimeMillis();
        this.saveBatch(list);
        log.info("批量插入耗时：{}", System.currentTimeMillis() - startTime);
        return list;
    }

    /**
     * 批量保存，自定义保存记录总数
     * @param totalRecord 总记录数
     * @param batchSize 自定义插入批次
     */
    public List<User> saveBatchByParam(int totalRecord, int batchSize) {
        List<User> list = new ArrayList<>();
        for (int i = 0; i < totalRecord; i++) {
            User user = new User();
            user.setUserName("name" + i);
            list.add(user);
        }
        super.saveBatch(list, batchSize);
        return list;
    }
}
